﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Sykj.ViewModel;

namespace Sykj.Components
{
    /// <summary>
    /// 提交模型表单验证注解类,
    /// ActionFilter过滤器的实现
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]//定义作用范围含类或方法
    public class ModelValidationAttribute: ActionFilterAttribute
    {
        /// <summary>
        /// 验证方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var modelState = context.ModelState;
            if (!modelState.IsValid)
            {
                //可以直接返回请求失败
                //context.Result = new BadRequestObjectResult(modelState);
                string error = string.Empty;
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        error = state.Errors.First().ErrorMessage;
                        break;
                    }
                }

                ApiResult apiResult = new ApiResult();
                apiResult.success = false;
                apiResult.code = (int)ApiEnum.ParameterError;
                apiResult.msg = error;

                context.Result = new JsonResult(apiResult);
            }
        }
    }
}
